package com.woman.beautylive.presentation.ui.login;

import android.util.Log;

import com.woman.beautylive.data.bean.BaseResponse;
import com.woman.beautylive.data.bean.LoginInfo;
import com.woman.beautylive.data.bean.ThirdLoginPlatform;
import com.woman.beautylive.domain.LocalDataManager;
import com.woman.beautylive.domain.LoginManager;
import com.woman.beautylive.presentation.ui.base.BaseObserver;
import com.woman.beautylive.presentation.ui.base.BasePresenter;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import rx.Subscription;

/**
 * @author Muyangmin
 * @since 1.0.0
 */
public class ThirdLoginPresenter extends BasePresenter<LoginUiInterface> {

    private LoginManager loginManager;

    public ThirdLoginPresenter(LoginUiInterface uiInterface) {
        super(uiInterface);
        loginManager = new LoginManager();
    }

    public void thirdLogin(Platform platform, final HashMap<String, Object> res){
        String openId = platform.getDb().getUserId();
        String platformName = formatPlatformName(platform);
        Subscription subscription = loginManager.thirdLogin(openId, platformName, res)
                .compose(this.<BaseResponse<LoginInfo>>applyAsySchedulers())
                .subscribe(new BaseObserver<BaseResponse<LoginInfo>>(getUiInterface()) {
                    @Override
                    public void onSuccess(BaseResponse<LoginInfo> response) {
                        LocalDataManager.getInstance().saveLoginInfo(response.getData());
                        getUiInterface().startActivityAndFinishOthers();
                    }
                })
        ;
        addSubscription(subscription);
    }

    @ThirdLoginPlatform
    private String formatPlatformName(Platform platform){
        String platformName;
        if (platform instanceof SinaWeibo){
            platformName = ThirdLoginPlatform.PLATFORM_SINA;
        }
        else if (platform instanceof QQ || platform instanceof QZone){
            platformName = ThirdLoginPlatform.PLATFORM_QQ;
        }
        else if (platform instanceof Wechat || platform instanceof WechatMoments){
            platformName = ThirdLoginPlatform.PLATFORM_WECHAT;
        }
        else {
            throw new IllegalArgumentException(String.format("Unsupported platform %s!", platform));
        }
        return platformName;
    }
}
